# -*- coding: utf-8 -*-
"""
Created on Sat May 27 21:42:53 2017

@author: Tubin Huang
"""

from PyQt4.QtGui import  QTableWidget, QApplication, QTableWidgetItem
from PyQt4.QtCore import Qt
import sys
import xml.etree.ElementTree as ET
OPERATION = "operation"

Null_XML = '<?xml version="1.0"?> \
<root operation = "null" > \
</data>"'

FIELDS = "fields"
ROW = "row"
NAME = "name"

test_xml = open("test.xml", 'r')

print test_xml

class ListView( QTableWidget ):
    def __init__( self, xmlStr = None ):
        super( ListView, self ).__init__()
        self.setAlternatingRowColors(True)
        if not xmlStr:    
            self.root_node =  ET.fromstring( Null_XML )
        else:
            self.root_node = ET.fromstring( xmlStr )
        
        self.setTable()
        
    def getFieldList( self ):
        headerList = []
        fields_node = self.root_node.find( FIELDS )
        for field in fields_node:
            headerList.append( field.text )
        return headerList

    def setHeaderLabes(self):
        headerList = self.getFieldList()
        rowCount = len(headerList)
        print rowCount
        count = 0
        while count < rowCount:
            self.insertRow( 0 )
            count = count + 1
            
        self.setVerticalHeaderLabels( headerList )
        
        
    
    def insertData( self, index, row_node ):
        self.insertColumn( index )
        fieldList = self.getFieldList()

        data = dict()        
        for item in row_node:
            field = item.attrib[ NAME ]
            text = item.text
            data[ field ] = text
            
        colIndex = 0
        for field in fieldList:
            text = unicode(data.get( field, "-"))
            item = QTableWidgetItem( text )
            item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter )
            self.setItem( colIndex, index, item )
            colIndex = colIndex + 1
            
    def insertDatas( self ):
        row_nodes = self.root_node.findall( ROW )
        index = 0
        for row_node in row_nodes:
            self.insertData( index, row_node )
            index = index + 1
            
    def setTable( self ):
        self.clear()
        
        self.setHeaderLabes()
        
        self.insertDatas()        
        
        """
        self.tableView.insertColumn()
        self.tableView.setItem()
        """
        


if __name__ == "__main__":
    
    app = 0
    app = QApplication(sys.argv)
    view = ListView( test_xml.read() )
    view.show()
    sys.exit(app.exec_())
    